if(!window.mc){
	window.mc = function(){};
}
window.mc.transport = function(){};

mc.transport.init = function(url){
	this.url = url;
	this.rid = 0;
}
mc.transport.send_message = function(msg){
	if(!msg.rid){
		msg.rid = ++this.rid;
	}
	msg.sid = mc.main.sid;
	if(!msg.chanel && mc.main.chanel){
		msg.chanel = mc.main.chanel;
	}
	return $.ajax({
		url: this.url + msg.cmd,
		type: "POST",
		dataType: "json",
		success: this.success_handler,
		processData: false,
		contentType: "text/x-javascript",
		data: $.toJSON(msg)
	});
}
mc.transport.success_handler = function(data){
	try{
		if(data.type && data.type == "list"){
			data.list.sort(function(a,b){return a.ats - b.ats});
			for(var i = 0; i < data.list.length; i++){
				mc.transport.response(data.list[i]);
			}
			mc.main.call_check();
		}else{
			mc.transport.response(data);
		}
	}catch(e){
		mc.tape.put_console("Err: " + e);
	}
}
mc.transport.response = function(data){
	switch(data.type){
		case "response":
			if(data.error){
				if(data.error == 401){
					mc.main.sid = "";
					mc.main.call_login();
				}else{
					mc.tape.put_console("Error: " + data.error + " " + data.text);
				}
			}else{
				mc.inputer.rewrite();
			}
			break;
		case "message":
			mc.tape.put_format_message(data);
			break;
		case "notice":
			switch(data.param1){
				case "welcome" :
					mc.tape.put_console("Добро пожаловать на канал <i>"+data.chaneltitle+"</i>, <b>" + data.title + "</b>.");
					mc.main.sid = data.sid;
					mc.main.chanel = data.chanel;
					mc.main.chanel_title = data.chaneltitle;
					mc.main.after_login();
					break;
				case "join":
					data.text = "Подключился [" + data.param2 + "].";
					mc.tape.put_format_message(data);
					break;
				case "leave":
					data.text = "Отключился [" + data.param2 + "].";
					mc.tape.put_format_message(data);
					break;
				case "list":
					if(data.param2 && data.param2.length > 0 ){
						data.text = "Список: [" + data.param2.join(", ") + "]";
					}else{
						data.text = "Список недоступен";
					}
					mc.tape.put_format_message(data);
					mc.inputer.rewrite();
					break;
				case "topic":
					mc.main.call_topic(data.param2);
					break;
				case "exec":
					mc.main.call_exec(data.param2);
					break;
			}
			break;
	}
}
